<template>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
          v-model="title"
          label="标题"
          placeholder="请输入文章标题"
          required
      />
    </van-cell-group>

    <van-field name="radio" label="单选框">
      <template #input>
        <van-radio-group v-model="category" direction="horizontal">
          <van-radio name="备考经验">备考经验</van-radio>
          <van-radio name="案例分析">案例分析</van-radio>
          <van-radio name="快题">快题</van-radio>
          <van-radio name="建筑史">建筑史</van-radio>
          <van-radio name="技术">技术</van-radio>
        </van-radio-group>
      </template>
    </van-field>

    <!-- 新增文本框用于输入文章内容 -->
    <van-field
        v-model="content"
        label="内容"
        type="textarea"
        rows="5"
        autosize
        placeholder="请输入文章内容"
        required
    />
  <div>
    <van-uploader
        :model-value="urlList"
        :after-read="handleRead"
        :max-size="5 * 1024 * 1024"
        :upload-text="'点击上传'"
    />
  </div>
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>
</template>

<script setup>

import {ref} from "vue";
import {post} from "../../util/request.js";
import {postFile} from "../../util/reqeustfile.js";
import axios from "axios";
const title = ref('');
const category = ref('备考经验'); // 默认选择备考经验
const content = ref('');
const urlList = ref([]);
const onSubmit = () => {
  // 发送请求到后端接口
  post('study/article/addArticle', {
    title: title.value,
    category: category.value,
    content: content.value,
    urlList: urlList.value
  })
      .then(response => {
        if (response.data.success) {
          console.log('Article created successfully');
          // 这里可以根据需要处理成功的逻辑，比如显示提示信息
          //清空数据
          title.value = '';
          category.value = '备考经验';
          content.value = '';
          urlList.value = [];
        } else {
        }
      }, error => {
        console.error('Error creating article:', error);
        // 处理错误逻辑
      });
    }
const handleRead =( async (file) =>{
  // console.log(file)
  // console.log(file.file)
  // const formData = new FormData();
  // formData.append('file', file.file); // 确保file.file是正确的，如果file就是文件对象，则应该是formData.append('file', file);

  // 发送POST请求到您的后端接口，确保传递formData且不包含多余的headers配置
  const response = await postFile('study/article/upload', file);
  urlList.value.push(response.data);
  console.log(urlList.value);
  // 这里可以根据需要处理成功的逻辑，比如显示提示信息
});
</script>

<style scoped>
.image-upload {
  /* Your custom styles */
}
</style>